<template>
  <div class="modal" v-show="isShowLoginModal">
    <!-- 遮罩 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <div class="loginbox">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <section class="nav">
        <a
          href="javascript:void(0);"
          :class="{ active: isShowPhone }"
          @click="isShowPhone = true"
          >手机号登录</a
        >
        |
        <a
          href="javascript:void(0);"
          :class="{ active: !isShowPhone }"
          @click="showQrCode"
          >微信扫码登录</a
        >
      </section>
      <div class="content">
        <div class="phone" v-show="isShowPhone">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="imags"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入短信验证码"
              v-model="codeVal"
            />
            <button @click="getcodeFn" v-show="showCode">获取验证码</button>
            <button v-show="!showCode" disabled style="background: gray">
              {{ count }}s后重新获取
            </button>
          </div>
          <div class="row">
            <button class="loginbtn" @click="submitFn">登录</button>
          </div>
        </div>
        <div class="qrbox" v-show="!isShowPhone" id="weixin"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from "vuex";
import { validatePhoneNumber } from "@/utils";
import { SendSMSAPI, PhoneReginAPI, BindingAPI } from "@/request/Api";
export default {
  data() {
    return {
      isShowPhone: true,
      msg: "向右滑动",
      phoneNumber: "",
      imags: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
        require("../assets/img/integral-04.afadcbdf.png"),
      ],
      showCode: true,
      count: 30,
      //  短信验证码
      codeVal: "",
    };
  },
  computed: {
    ...mapState({
      isShowLoginModal: (state) => state.showModal.isShowLoginModal,
    }),
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeLoginStatus: "loginStatus/changeLoginStatus",
    }),

    ...mapActions({
      asyncIsShowToast: "showToast/asyncIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),

    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    // 将电话号码和滑块校验统一处理
    toVerify() {
      //电话号码校验
      if (!validatePhoneNumber(this.phoneNumber)) {
        // 调用提示组件
        this.asyncIsShowToast({
          isShowToast: true,
          msg: "请输入正确的手机号码！",
          type: "danger",
        });

        return; //return之后没值则返回undefine
      }

      // 校验滑块
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        // 调用提示组件
        this.asyncIsShowToast({
          isShowToast: true,
          msg: "请滑动滑块验证码！！",
          type: "danger",
        });

        return;
      }
      return true;
    },

    // 获取验证码
    async getcodeFn() {
      // 调用校验方法
      let flag = this.toVerify();
      if (!flag) return;

      //获取验证码
      let res = await SendSMSAPI({
        phone: this.phoneNumber,
      });

      if (!res) return;
      if (res.code === 0) {
        // 验证成功
        let timer = setInterval(() => {
          if ((this.showCode = true)) {
            this.showCode = false;
            this.count--;
            if (this.count === 0) {
              clearInterval(timer), (this.count = 30);
              this.showCode = true;
            }
          }
        }, 1000);
      }
    },

    // 登录按钮事件
    async submitFn() {
      if (!this.toVerify()) return;

      // 短信验证码校验
      if (this.codeVal === "") {
        // 提示验证不能为空
        this.asyncIsShowToast({
          isShowToast: true,
          msg: "短信验证码不能为空！",
          type: "warning",
        });
        return;
      }

      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        // 微信绑定手机
        res = await BindingAPI({
          verifyCode: this.codeVal,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        res = await PhoneReginAPI({
          verifyCode: this.codeVal,
          phone: this.phoneNumber,
        });
        console.log("登录请求:", res);
        //判断res是否为undefine
        if (!res) return;
      }

      //1.成功提示
      this.asyncIsShowToast({
        isShowToast: true,
        msg: "登录成功！！",
        type: "success",
      });

      //2.存储token
      localStorage.setItem("x-auth-token", res["x-auth-token"]);

      //3.关闭模态框
      this.changeIsShowLoginModal(false);

      //4.改变登录变为购物车
      this.changeLoginStatus(true);

      // 删除uuid
      localStorage.removeItem("uuid");

      // 获取用户信息并更新到vuex数据
      this.asyncChangeUserInfo();
    },

    // 微信扫码登录
    showQrCode() {
      this.isShowPhone = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IHFyY29kZSB7DQogICAgbWFyZ2luLXRvcDogMjBweDsNCn0=",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .loginbox {
    width: 555px;
    height: 423px;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    background: url("../assets/img/login-box-bg.png");

    .close {
      width: 22px;
      height: 22px;
      position: absolute;
      right: 60px;
      top: 10px;
      background: url("../assets/img/close.png");
      cursor: pointer;
    }

    .nav {
      text-align: center;
      padding-top: 40px;
      color: #ccc;
      font-size: 18px;
      a {
        text-decoration: none;
        color: #ccc;
        &.active {
          color: #0a328e;
        }
      }
    }
    .content {
      width: 355px;
      margin: 20px auto 0;

      .phone {
        .row {
          display: flex;
          margin: 20px 0;
          input {
            flex: 1;
            height: 50px;
            outline: none;
          }
          button {
            background-color: #0a328e;
            cursor: pointer;
            border: 0;
            margin-left: 10px;
            color: white;
            font-size: 18px;
          }
          .loginbtn {
            flex: 1;
            height: 50px;
            margin-left: 0;
          }
        }
      }

      .qrbox {
        text-align: center;
      }
    }
  }
}

// 拼图
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>